#!/usr/bin/env python
# -*- coding: utf-8 -*-
# datetime: 18/12/2023 下午10:29
# Author: name
# File: login_api.py
# ide: PyCharm
# description:
from datetime import datetime
from typing import List

from fastapi import APIRouter, Query

from backend.app.models.login_model import LoginModel, LoginOut, LoginIn, LoginPage
from backend.app.utils.response_tepmlate import ResponseCode

login_router = APIRouter(prefix="/login", tags=["登录模板"])


# 定义 API 路由
@login_router.post("/add", response_model=LoginOut)
async def create_login(login: LoginIn):
    new_login = await LoginModel.create(
        name=login.name,
        login_temp=login.login_temp,
        description=login.description,
        created_at=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        updated_at=datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    )
    return new_login


# 获取登录模板列表（分页查询）
@login_router.get("/page", response_model=LoginPage)
async def get_login_page_list(
        page: int = Query(1, ge=1),
        size: int = Query(10, ge=1, le=100),
        name: str = Query(None, min_length=0)
):
    skip = (page - 1) * size
    query = LoginModel.all()
    if name:
        query = query.filter(name__icontains=name)
    total = await query.count()
    logins = await query.offset(skip).limit(size).values()
    return LoginPage(total=total, page_size=size, current_page=page, search_key=name, results=logins)


@login_router.get("/list", response_model=List[LoginOut])
async def read_login_list():
    return await LoginModel.all()


@login_router.get("/{login_id}", response_model=LoginOut)
async def get_login(login_id: int):
    login = await LoginModel.filter(id=login_id).first()
    if not login:
        return ResponseCode(login_id).response_404()
    return login


@login_router.put("/{login_id}", response_model=LoginOut)
async def update_login(login_id: int, login: LoginIn):
    await LoginModel.filter(id=login_id).update(
        name=login.name,
        login_temp=login.login_temp,
        description=login.description,
        updated_at=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    )
    updated_login = await LoginModel.filter(id=login_id).first()
    if not updated_login:
        return ResponseCode(login.name).response_404()
    return updated_login


@login_router.delete("/{login_id}")
async def delete_login(login_id: int):
    deleted_count = await LoginModel.filter(id=login_id).delete()
    if not deleted_count:
        return ResponseCode(login_id).response_404()
    return ResponseCode(f"{login_id}的登录模板").response_delete()